package com.sparkseries.common.security.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sparkseries.common.util.domain.Constants;
import com.sparkseries.common.util.domain.Result;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Objects;

/**
 * 登录失败处理器
 */
@Component
public class LoginFailureHandler implements AuthenticationFailureHandler {
    private Result<?> result;
    /**
     * 打印登录失败信息
     * @param request : 请求对象
     * @param response : 应答对象
     * @param exception : Spring Security 框架验证用户信息失败后的封装类
     * @throws IOException
     */
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException {
        // 当框架验证用户信息失败时执行的方法
        response.setContentType("text/json;charset:utf-8");
        if (Objects.isNull(request)) {
            result = new Result<>(Constants.LOGIN_FAIL, "登录失败", null);
        }

        OutputStream out = response.getOutputStream();
        ObjectMapper om = new ObjectMapper();
        om.writeValue(out, result);

        out.flush();
        out.close();
    }
}
